package com.ytktt.study.week9.task3.rpcfx.filter;

import com.google.common.collect.Lists;
import com.ytktt.study.week9.task3.rpcfx.constant.RpcfxConstant;
import org.reflections.Reflections;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 请求过滤器链配置
 *
 * @author ytk
 */
@Configuration
public class RequestFilterChainConfig {

    @Bean
    public RequestFilterChain requestFilterChain() throws Exception {
        Reflections refs = new Reflections(RpcfxConstant.SERVICE_PACKAGE_PREFIX);
        Set<Class<? extends RequestFilter>> requestFilters = refs.getSubTypesOf(RequestFilter.class);
        List<RequestFilter> filters = Lists.newArrayList();
        for (Class<? extends RequestFilter> requestFilterClazz : requestFilters) {
            filters.add(requestFilterClazz.newInstance());
        }
        filters = filters.stream().sorted(Comparator.comparingInt(RequestFilter::order)).collect(Collectors.toList());
        return new RequestFilterChain(filters);
    }
}
